const { getToken, getJWTPayload } = require('../middlewares/jwt');
const { saveSqlParse } = require('../common/utils');
const userModel = require('../model/user');
const { connect } = require("../model/index");

/**
 * 注册
 * @method: post
 * @param {*} ctx
 * @param {*} next
 */
const register = async (ctx, next) => {
  const query = ctx.request.body;
  const saveData = {
    username: query.username, // 账号
    phone: query.phone, // 手机号
    email: query.email, // 邮箱
    password: md5(query.password),
    create_time: Math.floor(Date.now() / 1000),
  };

  const database = userModel.TABLE_NAME;

  let [rows] = await connect.query(
    `select id from ${database} where phone = ? or username = ?`,
    [saveData.username, saveData.password]
  );
  if (rows[0]) {
    ctx.body = {
      data: null,
      code: 201,
      msg: '用户手机号或用户名已被注册',
    };
  }

  const { fields, values } = saveSqlParse(saveData);

  const connection = await connect.getConnection();

  try {
    // 开启事务
    await connection.beginTransaction();

    await connection.query(
      `
        INSERT INTO ${database}
        (${fields.join(',')})
        VALUES (${values.join(',')})
      `
    );
    await connection.commit();
  } catch (err) {
    await connection.rollback();
    ctx.throw(new Error(err));
  } finally {
    // connection.releaseConnection();
    connection.release();
  }

  ctx.body = {
    data: null,
    code: 200,
    msg: '操作成功',
  };
  await next();
}

/**
 * 登录
 * @method: post
 * @param {*} ctx
 * @param {*} next
 */
const userLogin = async (ctx, next) => {

  const { username, password } = ctx.request.query;

  let [rows] = await connect.query(
    `select id, username, realname from ${database} where username = ? and password = ?`,
    [query.username, password]
  );
  if (rows[0]) {

  }
  /*
    * query = {
    *  user : '御焱',
    *  password : '123456'
    * }
    */

  // TODO:判断 query.user 和 query.password 格式是否正确

  // TODO:判断是否已经注册
  
  // TODO:判断姓名、学号是否正确

  ctx.body = {
    code: 200,
    msg: 'success',
    data: {
      token: getToken({
        username: username,
        password: password
      })
    }
  }

  await next();
}

const getUserInfo = async (ctx, next) => {
  if (!ctx.headers.authorization) {
    ctx.body = {
      code: 202,
      data: {},
      msg: '没有传入token'
    }
  }

  let payload = '666'
  try {
    payload = getJWTPayload(ctx.headers.authorization);
  } catch (err) {
    ctx.body = {
      code: 202,
      data: {},
      msg: err
    }
  }

  // 前端访问时会附带token在请求头
  // let payload = getJWTPayload(ctx.headers.authorization);

  // 根据 payload.user 查询该用户在数据库中的信息
  // 待办事项……

  let isInfo = true;
  if (isInfo) {
    ctx.body = {
      code: 200,
      msg: 'success',
      data: payload
    };
  }

  await next();
}

const users = async (ctx, next) => {
  let [ rows, fields ] = await connect.query('select * from blog_category where `id` = ?', [ctx.request.query.uid]);

  // let [ rows, fields ] = await connect.query(`insert into blog_article (category_id,title,content,create_time,description,access_num) values (1,213,'详情','1611208827','描述',?) `, [ctx.request.query.uid]);

  // let err = connect.rollback();
  const conf = require('../config/index.js');
  // console.log(conf)

  console.log(ctx.url.replace(/(^\/\w*)[\/\?].*/gi, '$1'))

  ctx.body = {
    data: rows,
    code: 200,
  };
}

module.exports = {
  register,
  userLogin,
  getUserInfo,
  users
}